//
//  HMPhoneNumLoginViewController.m
//  获得
//
//  Created by mac on 17/1/7.
//  Copyright © 2017年 mac.gu. All rights reserved.
//
#import "SGSaveFile.h"
#import "HMPhoneNumChangeViewController.h"
#import "HMPhoneNumLoginViewController.h"
#import "HMPhoneNumForgetViewController.h"
#import "HMPhoneLoginViewModel.h"
#import "UIViewController+Extension.h"
#import "HMPhoneNum.h"
#import "HMSetInformationViewController.h"

#import "HMUserInfoTools.h"
#import "TPKeyboardAvoidingScrollView.h"
#import "HMUserInfoModel.h"
#import "HMMainViewController.h"
@interface HMPhoneNumLoginViewController ()

//用户名
@property (nonatomic, strong) UITextField *txtUserName;

//密码
@property (nonatomic, strong) UITextField *txtPassWord;

//记住我
@property (nonatomic, strong) UIButton * btnRemember;
//忘记密码
@property (nonatomic, strong) UIButton *btnForgetPassWord;
//修改密码
@property (nonatomic, strong) UIButton *btnChengePassWord;
//立即登陆
@property (nonatomic, strong) UIButton *btnLogin;



@end

@implementation HMPhoneNumLoginViewController

#define RememberMe @"HM_RememberMe"
#define UserName @"HM_UserName"


- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"返回";
    self.navigationItem.backBarButtonItem = backItem;
    self.view = [[TPKeyboardAvoidingScrollView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    [self setupUI];

    
}

- (void)setupUI{
    self.title = @"登录";
    self.view.backgroundColor = [UIColor whiteColor];
    //添加用户名
    [self.view addSubview:self.txtUserName];
    [_txtUserName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.top.offset(84);
        make.centerX.equalTo(self.view);
        make.height.offset(40);
    }];

    
    //添加输入密码
    [self.view addSubview:self.txtPassWord];
    [_txtPassWord mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_txtUserName);
        make.top.equalTo(_txtUserName.mas_bottom).offset(20);
        make.height.equalTo(_txtUserName);
    }];
    
    
    //设置记住我
    [self.view addSubview:self.btnRemember];
    [_btnRemember mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_txtUserName);
        make.top.equalTo(_txtPassWord.mas_bottom).offset(15);
        make.width.offset(100);
        make.height.equalTo(_txtUserName);
    }];
    //修改密码
    [self.view addSubview:self.btnChengePassWord];
    [_btnChengePassWord mas_makeConstraints:^(MASConstraintMaker *make) {
       make.bottom.equalTo(_btnRemember);
        make.height.equalTo(_btnRemember);
        make.left.equalTo(_btnRemember.mas_right).offset(60);
    }];
    //忘记密码
    [self.view addSubview:self.btnForgetPassWord];
    [_btnForgetPassWord mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_txtUserName);
        make.height.equalTo(_btnRemember);
        make.bottom.equalTo(_btnRemember);
        make.left.equalTo(_btnChengePassWord.mas_right).offset(5);
    }];
    
    

    [self.view addSubview:self.btnLogin];
    [_btnLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view);
        make.width.equalTo(_txtPassWord);
        make.height.offset(40);
    }];

}

//输入用户名
- (UITextField *)txtUserName{
    if (!_txtUserName) {
        _txtUserName = [[UITextField alloc] init];
        
        if ([SGSaveFile getObjectFromSystemWithKey:RememberMe]&&[[SGSaveFile getObjectFromSystemWithKey:UserName] length]>0) {
            _txtUserName.text = [SGSaveFile getObjectFromSystemWithKey:UserName];
        }
        //是否纠错
        _txtUserName.autocorrectionType = UITextAutocorrectionTypeNo;
        _txtUserName.keyboardType = UIKeyboardTypeNumberPad;
        _txtUserName.font = [UIFont systemFontOfSize:18];
        _txtUserName.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入手机号" attributes:@{NSForegroundColorAttributeName: [UIColor colorWithHex:0x999999]}];
        
        _txtUserName.textColor = [UIColor orangeColor];
        _txtUserName.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        _txtUserName.layer.borderWidth = 0.5;
        _txtUserName.layer.masksToBounds = YES;
        _txtUserName.layer.cornerRadius = 4;
        _txtUserName.backgroundColor = [UIColor colorWithHex:0xffffff];
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];
        _txtUserName.leftView = img;
        _txtUserName.leftViewMode = UITextFieldViewModeAlways;
        
        
    }
    return _txtUserName;
}


//输入密码
- (UITextField *)txtPassWord{
    if (!_txtPassWord) {
        _txtPassWord = [[UITextField alloc] init];

        if ([[SGSaveFile getObjectFromSystemWithKey:RememberMe] length] >0) {
            ;
        }
        
        _txtPassWord.autocorrectionType = UITextAutocorrectionTypeNo;
        _txtPassWord.font = [UIFont systemFontOfSize:18];
        _txtPassWord.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName: [UIColor colorWithHex:0x999999]}];
        _txtPassWord.secureTextEntry = YES;
        
        _txtPassWord.textColor = [UIColor orangeColor];
        _txtPassWord.layer.borderColor = [UIColor colorWithHex:0xcccccc].CGColor;
        _txtPassWord.layer.borderWidth = 0.5;
        _txtPassWord.layer.masksToBounds = YES;
        _txtPassWord.layer.cornerRadius = 4;
        _txtPassWord.backgroundColor = [UIColor colorWithHex:0xffffff];
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];
        _txtPassWord.leftView = img;
        
        _txtPassWord.leftViewMode = UITextFieldViewModeAlways;
    }
    return _txtPassWord;
}


//记住我
- (UIButton *)btnRemember{
    if (!_btnRemember) {
        _btnRemember = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnRemember setImage:[UIImage imageNamed:@"记住我_未勾选"] forState:UIControlStateNormal];
        [_btnRemember setImage:[UIImage imageNamed:@"记住我_勾选"] forState:UIControlStateSelected];
        _btnRemember.titleLabel.font = [UIFont systemFontOfSize:13];
        [_btnRemember setTitle:@" 记住我" forState:UIControlStateNormal];
        
        [_btnRemember setTitleColor:[UIColor colorWithHex:0x888888] forState:UIControlStateNormal];
        [_btnRemember addTarget:self action:@selector(btnRememberClick:) forControlEvents:UIControlEventTouchUpInside];
        _btnRemember.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        
#warning 记住密码按钮存储
        if ([SGSaveFile getObjectFromSystemWithKey:RememberMe]) {
            _btnRemember.selected = YES;
        }
    }
    return _btnRemember;
}
//忘记密码
- (UIButton *)btnForgetPassWord{
    if (!_btnForgetPassWord) {
        _btnForgetPassWord = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_btnForgetPassWord setTitleColor:[UIColor colorWithHex:0x888888] forState:UIControlStateNormal];
        _btnForgetPassWord.titleLabel.font = [UIFont systemFontOfSize:13];
        [_btnForgetPassWord setTitle:@"忘记密码" forState:UIControlStateNormal];
        [_btnForgetPassWord sizeToFit];
        
        [_btnForgetPassWord addTarget:self action:@selector(btnForgetPassWordAction) forControlEvents:UIControlEventTouchUpInside];

    }
    return _btnForgetPassWord;
}

//修改密码
- (UIButton *)btnChengePassWord{
    if (!_btnChengePassWord) {
        _btnChengePassWord = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_btnChengePassWord setTitleColor:[UIColor colorWithHex:0x888888] forState:UIControlStateNormal];
        _btnChengePassWord.titleLabel.font = [UIFont systemFontOfSize:13];
        [_btnChengePassWord setTitle:@"修改密码" forState:UIControlStateNormal];
        [_btnChengePassWord sizeToFit];
        
        [_btnChengePassWord addTarget:self action:@selector(btnChengePassWordAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _btnChengePassWord;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

//立即登录
- (UIButton *)btnLogin{
    if (!_btnLogin) {
        _btnLogin = [UIButton buttonWithType:UIButtonTypeCustom];
        
        [_btnLogin setTitleColor:[UIColor colorWithHex:0xffffff] forState:UIControlStateNormal];
        _btnLogin.titleLabel.font = [UIFont systemFontOfSize:17];
        [_btnLogin setTitle:@"立即登录" forState:UIControlStateNormal];
        _btnLogin.layer.masksToBounds = YES;
        _btnLogin.layer.cornerRadius = 5;
        _btnLogin.backgroundColor = [UIColor orangeColor];
        
        [_btnLogin addTarget:self action:@selector(btnLogInAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _btnLogin;
}

- (void)btnRememberClick:(UIButton *)button{
    button.selected = !button.selected;
    if (!button.selected) {
        [SGSaveFile removeObjectFromSystemWithKey:RememberMe];
    }
}
//修改密码跳转
- (void)btnChengePassWordAction{
    HMPhoneNumChangeViewController *changePassWordVc= [[HMPhoneNumChangeViewController alloc] init];
    changePassWordVc.view.backgroundColor = [UIColor colorWithHex:0xffffff];
    
    [self.navigationController pushViewController:changePassWordVc animated:YES];
    
}
-(void)btnForgetPassWordAction{
    //忘记密码跳转
    HMPhoneNumForgetViewController *forgetPassWordVc= [[HMPhoneNumForgetViewController alloc] init];
    forgetPassWordVc.view.backgroundColor = [UIColor colorWithHex:0xffffff];
    [self.navigationController pushViewController:forgetPassWordVc animated:YES];
}



-(void)btnLogInAction{
    
    

    
    //立即登录
    [self showHudWaitingView:@"请稍后..."];
    if ([HMPhoneNum isMobile:self.txtUserName.text] != YES) {
        [self showHudAuto:@"请输入正确手机号" andDuration:@"1"];
    }else if ([self.txtPassWord.text isEqualToString:@""]) {
        [self showHudAuto:@"请输入密码" andDuration:@"1"];
    }else{
        
        if (self.btnRemember.selected) {
            [SGSaveFile saveObjectToSystem:RememberMe forKey:RememberMe];
            [SGSaveFile saveObjectToSystem:self.txtUserName.text forKey:UserName];
            
        } else{
            [SGSaveFile removeObjectFromSystemWithKey:UserName];
            
        }
        
        WeakSelf(HMPhoneNumLoginViewController);
        
        NSString *token =[[NSUserDefaults standardUserDefaults]objectForKey:@"idToken"];
        
        if (token == nil) {
            
            [self showHudAuto:@"请注册,或账号密码失败" andDuration:@"2"];
            return ;
        }
        
        
        [HMPhoneLoginViewModel postPhoneNumLogin:_txtUserName.text andPassword:_txtPassWord.text andToken:token Finished:^(id responseObject) {
            [weakSelf removeMBProgressHudInManaual];
            //登录成功 跳转主界面response.Code == 1
            NSString *code = responseObject[@"code"];
            NSInteger intCode = code.integerValue;
            if (intCode == 200 ) {
                //登录成功
                if (weakSelf.btnRemember.selected) {
                    [SGSaveFile saveObjectToSystem:RememberMe forKey:RememberMe];
                    [SGSaveFile saveObjectToSystem:self.txtUserName.text forKey:UserName];
                    
                }//保存token
                
//                [weakSelf showHudAuto:@"登录成功" andDuration:@"2"];
                
                HMUserInfoModel *model = [[HMUserInfoModel alloc]init];
                
                model.token = responseObject[@"data"][@"token"];
                model.phone_num = responseObject[@"data"][@"phone_num"];
                model.user_id = responseObject[@"data"][@"user_id"];
                
                
                [[HMUserInfoTools shareUserInfo] saveModel:model];
                
                if (self.isGuide) {
                    
                    
                    HMMainViewController *mainVC = [[HMMainViewController alloc] init];
                    //  切换跟视图控制器
                    [UIApplication sharedApplication].keyWindow.rootViewController = mainVC;
                } else {
                    //  发送登录成功通知
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"loginSuccess" object:nil];
                    
                    
                    //  回到根视图dismis
                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                    
                    
                    [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
                }
                
                
               
                
            }else{
                
                [weakSelf showHudAuto:@"账号或密码错误" andDuration:@"2"];
            }
            
            
        } Failed:^(NSError *error) {
//            网络有波动，请重新尝试
            [weakSelf showHudAuto:@"网络有波动，请重新尝试" andDuration:@"2"];
            
        }];
    }
    
    
}




@end
